import {useDocument, useCollection} from "@nandorojo/swr-firestore";
import {useRouter} from "next/router";

import * as React from "react";

import AuthContext from "@sentrei/common/context/AuthContext";
import Member from "@sentrei/common/models/Member";
import Space from "@sentrei/common/models/Space";
import {analytics} from "@sentrei/common/utils/firebase";
import Loader from "@sentrei/ui/components/Loader";
import SpaceScreen from "@sentrei/ui/components/SpaceScreen";
import useSnackbar from "@sentrei/ui/hooks/useSnackbar";
import SentreiAppHeader from "@sentrei/web/components/SentreiAppHeader";

const Spaces = (): JSX.Element => {
  const router = useRouter();
  const {id} = router.query;
  const {snackbar} = useSnackbar();

  const {data: space, error} = useDocument<Space.Get>(`spaces/${id}`);
  const {data: members} = useCollection<Member.Get>(
    space?.id ? `spaces/${space.id}/members` : null,
  );

  const {user} = React.useContext(AuthContext);

  React.useEffect(() => {
    analytics().setCurrentScreen("spaces");
  }, []);

  if (user === undefined) {
    return <Loader />;
  }

  if (!user) {
    router.push("/");
  }

  if (error) {
    snackbar("error", error?.message);
  }

  return (
    <>
      <SentreiAppHeader />
      {user && <SpaceScreen space={space} members={members} />}
    </>
  );
};

export default Spaces;
